const WXAPI = require('apifm-wxapi')
const AUTH = require('../../utils/auth')
const TOOLS = require('../../utils/tools.js') // TOOLS.showTabBarBadge();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    categories: [],
    activeCategory: 0,
    categorySelected: {
      name: '',
      id: ''
    },
    currentGoods: [],
    currentGoodsNewList: [],
    onLoadStatus: true,
    scrolltop: 0,
    skuCurGoods: undefined,
    page: 1,
    pageSize: 20,
    totalPage: 0, //分页总数
    ordersSort: true, //销量排序
    priceSort: true, //价格排序
    sortObj: {}, //排序参数
    isRefreshing: true,
    scrolVievlTop: 0,
    scrollVievHeight: 0,

    goodsIsGoBottom: true,


  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showShareMenu({
      withShareTicket: true
    })
    this.setData({
      categoryMod: wx.getStorageSync('categoryMod')
    })
    this.categories();


  },

  onUnload() {
    // if (this._observer) this._observer.disconnect()
  },
  async categories(isClickTabs) {
    wx.showLoading({
      title: '',
    })
    const res = await WXAPI.goodsCategory()
    wx.hideLoading()
    let activeCategory = 0
    let categorySelected = this.data.categorySelected
    if (res.code == 0) {
      const categories = res.data.filter(ele => {
        //410490 为新人专享页面不展示
        return !ele.vopCid1 && !ele.vopCid2
      })
      categories.forEach(p => {
        p.childs = categories.filter(ele => {
          return p.id == ele.pid
        })
      })
      const firstCategories = categories.filter(ele => {
        return ele.level == 1
      })
      if (this.data.categorySelected.id) {
        activeCategory = firstCategories.findIndex(ele => {
          return ele.id == this.data.categorySelected.id
        })
        categorySelected = firstCategories[activeCategory]
      } else {
        categorySelected = firstCategories[0]
      }
      const resAd = await WXAPI.adPosition('category_' + categorySelected.id)
      let adPosition = null
      if (resAd.code === 0) {
        adPosition = resAd.data
      }
      this.setData({
        page: 1,
        activeCategory,
        categories,
        firstCategories,
        categorySelected,
        adPosition
      }, () => {
    
        this.getGoodsList(isClickTabs)
      })
    }
  },
  async getGoodsList(isCategoryClick) {
    if (this.data.categoryMod == 2) {
      return
    }
    // if(this.data.page>this.data.totalPage){
    //   return
    // }
    wx.showLoading({
      title: '',
    })
    // secondCategoryId
    let categoryId = ''
    if (this.data.secondCategoryId) {
      categoryId = this.data.secondCategoryId
    } else if (this.data.categorySelected?.id) {
      categoryId = this.data.categorySelected.id
    }
    if (!categoryId) {
      wx.hideLoading()
      return
    }

    // https://www.yuque.com/apifm/nu0f75/wg5t98
    const res = await WXAPI.goodsv2({
      ...this.data.sortObj,
      categoryId,
      page: this.data.page,
      pageSize: this.data.pageSize
    })
    wx.hideLoading()
    if (res.code == 700) {
      const idx = this.data.firstCategories.findIndex((ele) => ele.id === categoryId)
      if (this.data.page == 1 && idx > -1) {
        // this.setData({
        //   currentGoods: this.data.currentGoods?.concat([]),
        //   currentGoodsNewList: this.data.currentGoodsNewList?.concat([]),
        //   activeCategory: idx
        // });

        if (isCategoryClick) {
          this.setData({
            currentGoods: res.data?.result || null,
            totalPage: res.data?.totalPage || 0,
            currentGoodsNewList: res.data?.result || null,
            goodsIsGoBottom: true,
          })
        } else {
          const reslist = await WXAPI.goodsv2({
            ...this.data.sortObj,
            categoryId: this.data.firstCategories[idx + 1]?.id,
            page: 1,
            pageSize: this.data.pageSize
          })
          let list = this.newAaray(this.data.currentGoods?.concat(reslist.data?.result || []))
          this.setData({
            currentGoods: this.data.currentGoods?.concat(reslist.data?.result || []),
            totalPage: res.data?.totalPage || 0,
            currentGoodsNewList: list.sort((a, b) => a.sortNum - b.sortNum),
            categorySelected: this.data.firstCategories[idx + 1],
            goodsIsGoBottom: true,
          })
        }


      } else {
        // wx.showToast({
        //   title: '没有更多了',
        //   icon: 'none'
        // })

      }
      return
    }
    if (res.code != 0) {
      wx.showToast({
        title: res.msg,
        icon: 'none'
      })
      return
    }
    let goodsClassify = this.newAaray(this.data.currentGoods?.concat(res.data?.result || []))
    let resultList = this.newAaray((res.data?.result || []))
    // this.data.currentGoods?.concat(res.data.result || []).map((i) => {
    //   if (!goodsClassify.find((ele) => ele.categoryId === i.categoryId)) {
    //     goodsClassify.push({
    //       typeNmae: this.data.firstCategories?.find((it) => it.id === i.categoryId).name,
    //       categoryId: i.categoryId,
    //       sotrNum: i.paixu,
    //       list: [i]
    //     })
    //   } else {
    //     goodsClassify.forEach((item) => {
    //       if (item.categoryId === i.categoryId) {
    //         item.list.push(i)
    //       }
    //     })
    //   }
    // });
    // (res.data.result || []).map((i) => {
    //   if (!resultList.find((ele) => ele.categoryId === i.categoryId)) {
    //     resultList.push({
    //       typeNmae: this.data.firstCategories?.find((it) => it.id === i.categoryId).name,
    //       categoryId: i.categoryId,
    //       sortNum: i.paixu,
    //       list: [i]
    //     })
    //   } else {
    //     resultList.forEach((item) => {
    //       if (item.categoryId === i.categoryId) {
    //         item.list.push(i)
    //       }
    //     })
    //   }
    // });
    if (this.data.page == 1) {
      this.setData({
        currentGoods: isCategoryClick ? res.data.result : this.data.currentGoods?.concat(res.data.result || []),
        totalPage: res.data.totalPage,
        currentGoodsNewList: isCategoryClick ? resultList : goodsClassify.sort((a, b) => a.sortNum - b.sortNum),
        goodsIsGoBottom: true,
      })
    } else {
      this.setData({
        currentGoods: isCategoryClick ? res.data.result : this.data.currentGoods?.concat(res.data.result || []),
        currentGoodsNewList: isCategoryClick ? resultList : goodsClassify.sort((a, b) => a.sortNum - b.sortNum),
        goodsIsGoBottom: true,
      })
    }
  },
  newAaray(arr) {
    let resultList = []
    arr?.map((i) => {
      if (!resultList.find((ele) => ele.categoryId === i.categoryId)) {
        resultList.push({
          typeNmae: this.data.firstCategories?.find((it) => it.id === i.categoryId).name,
          categoryId: i.categoryId,
          sortNum: i.paixu,
          list: [i]
        })
      } else {
        resultList.forEach((item) => {
          if (item.categoryId === i.categoryId) {
            item.list.push(i)
          }
        })
      }
    });
    return resultList

  },
  async clickSort(e) {
    const type = e.currentTarget.dataset.type
    const {
      ordersSort,
      priceSort
    } = this.data
    let sortObj = {}
    switch (type) {
      case "orders":
        sortObj = {
          orderBy: ordersSort ? "ordersUp" : "ordersDown"
        }
        this.data.ordersSort = !ordersSort
        break;
      case "price":
        sortObj = {
          orderBy: priceSort ? "priceUp" : "priceDown"
        }
        this.data.priceSort = !priceSort
        break;
      default:
        sortObj = {}
        break;
    }
    const categorySelected = this.data.firstCategories[0]
    const res = await WXAPI.adPosition('category_' + categorySelected.id)
    let adPosition = null
    if (res.code === 0) {
      adPosition = res.data
    }
    this.setData({
      secondCategoryId: '',
      categorySelected,
      activeCategory: 0,
      scrolltop: 0,
      adPosition
    }, () => {
      this.data.page = 1
      this.data.sortObj = sortObj
      this.getGoodsList(true)

    });
  },
  async onCategoryClick(e, isCategoryClick = true) {
    const idx = e.target.dataset.idx
    if (idx == this.data.activeCategory) {
      // this.setData({
      //   scrolltop: 0,
      // })
      return
    }
    const categorySelected = this.data.firstCategories[idx]

    const res = await WXAPI.adPosition('category_' + categorySelected.id)
    let adPosition = null
    if (res.code === 0) {
      adPosition = res.data
    }
    this.data.page = 1
    this.setData({
      secondCategoryId: '',
      categorySelected,
      activeCategory: idx,
      adPosition
    });
    if (isCategoryClick) {
      this.setData({
        scrolltop: 0,

      })
    }

    this.getGoodsList(Boolean(isCategoryClick));
  },
  onSecondCategoryClick(e) {
    const idx = e.detail.index
    let secondCategoryId = ''
    if (idx) {
      // 点击了具体的分类
      secondCategoryId = this.data.categorySelected.childs[idx - 1].id
    }
    this.setData({
      page: 1,
      secondCategoryId
    });
    this.getGoodsList(true);
  },
  bindconfirm(e) {
    this.setData({
      inputVal: e.detail
    })
    wx.navigateTo({
      url: '/pages/goods/list?name=' + this.data.inputVal,
    })
  },
  onShareAppMessage() {
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + wx.getStorageSync('share_profile'),
      path: '/pages/index/index?inviter_id=' + wx.getStorageSync('uid')
    }
  },
  onShareTimeline() {
    return {
      title: '"' + wx.getStorageSync('mallName') + '" ' + wx.getStorageSync('share_profile'),
      query: '',
      imageUrl: this.data.goodsDetail.basicInfo.pic
    }
  },
  onShow() {
    AUTH.checkHasLogined().then(isLogined => {
      if (isLogined) {
        this.setData({
          wxlogin: isLogined
        })
        TOOLS.showTabBarBadge() // 获取购物车数据，显示TabBarBadge
      }
    })
    const _categoryId = wx.getStorageSync('_categoryId')
    wx.removeStorageSync('_categoryId')
    if (_categoryId) {
      this.data.categorySelected.id = _categoryId
      this.categories(true);
      this.setData({
        scrolltop: 0
      })
    }

  },
  async addShopCar(e) {
    const curGood = this.data.currentGoods.find(ele => {
      return ele.id == e.currentTarget.dataset.id
    })
    if (!curGood) {
      return
    }
    if (curGood.stores <= 0) {
      wx.showToast({
        title: '已售罄~',
        icon: 'none'
      })
      return
    }
    if (!curGood.propertyIds && !curGood.hasAddition) {
      // 直接调用加入购物车方法
      const res = await WXAPI.shippingCarInfoAddItem(wx.getStorageSync('token'), curGood.id, 1, [], [], wx.getStorageSync('shopIds'))
      console.log(res);
      if (res.code == 30002) {
        // 需要选择规格尺寸
        this.setData({
          skuCurGoods: curGood
        })
      } else if (res.code == 0) {
        wx.showToast({
          title: '加入成功',
          icon: 'success'
        })
        wx.showTabBar()
        TOOLS.showTabBarBadge() // 获取购物车数据，显示TabBarBadge
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    } else {
      // 需要选择 SKU 和 可选配件
      this.setData({
        skuCurGoods: curGood
      })
    }
  },

  goodsGoBottom(e) {
    if (!this.data.goodsIsGoBottom) {
      return
    }
    this.data.goodsIsGoBottom = false
    if (this.data.page + 1 > this.data.totalPage) {
      const idx = this.data.firstCategories.findIndex((i) => i.id === this.data.categorySelected.id)
      if (idx === -1 || ((idx + 1) >= this.data.firstCategories?.length)) {
        return
      }
     
      this.data.categorySelected = this.data.firstCategories[idx + 1]
      this.data.page = 1
      this.getGoodsList(false)
    } else {
      this.data.page++
      this.getGoodsList(false)
    }
  },
  adPositionClick(e) {
    const url = e.target.dataset.url
    if (url) {
      wx.navigateTo({
        url: url
      })
    }
  },
  searchscan() {
    wx.scanCode({
      scanType: ['barCode', 'qrCode', 'datamatrix', 'pdf417'],
      success: res => {
        this.setData({
          inputVal: res.result
        })
        wx.navigateTo({
          url: '/pages/goods/list?name=' + res.result,
        })
      }
    })
  },
  refresherstatuschange() {
    let idx = this.data.activeCategory;
    if (idx === 0) {
      this.setData({
        isRefreshing: false
      })
      return
    }
    idx = idx - 1
    this.onCategoryClick({
      target: {
        dataset: {
          idx
        }
      }
    })
    this.setData({
      isRefreshing: false
    })
  },
  goodsScroll(event) {
    const isUpglide = event.detail.deltaY > 0
    const scroll = wx.createSelectorQuery()
    scroll.selectAll(".goods-container-scroll").boundingClientRect()
    scroll.exec(async (scrollViev) => {
      const viewHig = await wx.getSystemInfo()
      const query = wx.createSelectorQuery()
      query.selectAll("#typeName").boundingClientRect()
      query.exec(res => {
        const findVievlist = res[0].filter((i) => (i.top < viewHig.windowHeight - 50 && i.top > 0));
        if (!findVievlist.length) {
          return
        }
        const firstCategoriesIdx = this.data.firstCategories.findIndex((ele) => ele.id === findVievlist[0]?.dataset?.id)
        const loc = parseInt(findVievlist[0].top) - parseInt(scrollViev[0][0].top)
        if (loc < 0) {
          if ((firstCategoriesIdx > -1)) {
            this.setData({
              activeCategory: firstCategoriesIdx + 1
            })
          }
        } else if (loc > 0 && loc < 200 && isUpglide) {

          this.setData({
            activeCategory: firstCategoriesIdx
          })

        }
      })

    })

  }
})